package net.newsmth.smthapp.android.config;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;

import net.newsmth.libSMTH.SMTHURLConnection;
import net.newsmth.libSMTH.smth_netop;
import net.newsmth.smthapp.android.common.util.BooleanUtil;

import org.json.JSONArray;
import org.json.JSONException;

/**
 * Created by Hatsune Miku on 3/26/14.
 */
public class SmthConnection {


    //<editor-fold desc="static members">
    public static int SMTH_NETWORK_HANDLER = 1;
    public static String SMTH_NETWORK_STATUS_TYPE_KEY = "SMTH_NETWORK_STATUS_TYPE_KEY";
    public static String SMTH_NETWORK_Error_DESCRIPTION_KEY = "SMTH_NETWORK_Error_DESCRIPTION_KEY";

    public static final SmthConnection getCurrent() {
        return SmthConnectionHolder.holdObject;
    }
    //</editor-fold>

    private SMTHURLConnection conn;
    private smth_netop netop;
    private Handler handler;


    public SmthConnection()
    {
        netop = smth_netop.getInstance();
        conn = new SMTHURLConnection();
        conn.init_smth(new Handler());
    }

    //<editor-fold desc="Public methods">
    public SmthNetStatusType getErrorType() {
        SmthNetStatusType returnValue = SmthNetStatusType.convertFromErrorCode(conn.net_error);

        // smth api has some bug, it can't return the "无效的access_token" error
        if (returnValue == SmthNetStatusType.OK && (conn.net_error_desc != null) && conn.net_error_desc.contains("无效的access_token")) {
            returnValue = SmthNetStatusType.TOKEN_FAILURE;
        }

        return returnValue;
    }

    public String getErrorDescription() {
        return conn.net_error_desc;
    }

    public Handler getHandler() {
        return this.handler;
    }

    public void setHandler(Handler handler) {
        this.handler = handler;
        conn.init_smth(handler);
    }

    public boolean login(String userName, String password) {
        int result = conn.net_LoginBBS(userName, password);
        checkNetworkStatus();
        return BooleanUtil.parseInt(result);
    }

    public String getToken() {
        return netop.apiGetAccessToken();
    }

    public JSONArray getThreadArticles(String boardid, long threadId, long from, long size, int sortDirection) {
        return conn.net_GetThread(boardid, threadId, from, size, sortDirection);
    }

    public boolean login(String token) {
        netop.apiSetAccessToken(token);

        // To resolve an api bug. Call an api function to check if token is right.
        conn.net_GetMailCount();
        checkNetworkStatus();
        return this.getErrorType() == SmthNetStatusType.OK;
    }

    public void logout() {
        checkNetworkStatus();
        conn.net_LogoutBBS();
    }

    public String getServerJson_Test(String s1, String s2, String s3, long l1, long l2, long l3) {
        JSONArray array = conn.net_GetThread(s1, l1, 0, 1, 0);

        if (array.length() > 0) {
            try {
                return array.get(0).toString();
            } catch (JSONException ex)
            {}
        }
        return "";
    }

    public JSONArray getSectionHot(long sectionId) {
        checkNetworkStatus();
        return conn.net_LoadSectionHot(sectionId);
    }

    public int getMailCountSent() {
        checkNetworkStatus();
        return conn.net_GetMailCountSent();
    }
    //</editor-fold>

    private void checkNetworkStatus() {
        if (handler != null) {
            
            Message message = handler.obtainMessage(SMTH_NETWORK_HANDLER);
            Bundle data= new Bundle();
            data.putString(SMTH_NETWORK_STATUS_TYPE_KEY, getErrorType().toString());
            data.putString(SMTH_NETWORK_Error_DESCRIPTION_KEY, getErrorDescription());
            message.setData(data);
            message.sendToTarget();
        }
    }

    /**
     * Use for implement the singleton
     */
    private static class SmthConnectionHolder {
        private static final SmthConnection holdObject = new SmthConnection();
    }

}
